<?php

namespace app\admin\controller\express;

use app\admin\library\Ehund;
use app\admin\model\express\OrderAddress;
use app\common\controller\Backend;
use app\common\model\Category;
use Com\Tecnick\Pdf\Font\Load;
use think\Config;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Loader;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Package extends Backend
{
    
    /**
     * Package模型对象
     * @var \app\admin\model\express\Package
     */
    protected $model = null;
    protected $searchFields = 'id,package_no,express_no';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\express\Package;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("deliveryStatusList", $this->model->getDeliveryStatusList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        $batch_id = $this->request->param('ids');
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $batch_id = (int)$this->request->param('batch_id');
            $w = [];

            if($batch_id>0){
                $w['batch_id'] = $batch_id;
            }


            $list = $this->model
                    ->with(['batch','expressorder','user','address'])
                    ->where($where)
                    ->where($w)
                    ->order($sort, $order)
                    ->paginate($limit);

          //  $sql = $this->model->getLastSql();
          //  dump($sql);die;


            foreach ($list as $row) {
                
                $row->getRelation('batch')->visible(['batch_no']);
				$row->getRelation('expressorder')->visible(['order_no']);
				$row->getRelation('user')->visible(['nickname','avatar']);
				$row->getRelation('address')->visible(['name','idcard','mobile']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $this->assignconfig('batch_id',$batch_id);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids,['expressorder','user','goods']);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $express = model('\app\admin\model\express\Express')->where([
                        'express_com' => $params['express_com'],
                        'express_no' => $params['express_no'],
                        'status' => 'created',
                    ])->lock(true)->find();
                    if(!$express){
                        $this->error('该物流单号不存在');
                    }
                    model('\app\admin\model\express\Express')->where([
                        'express_com' => $params['express_com'],
                        'express_no' => $params['express_no'],
                    ])->update([
                        'status' => 'used',
                        'usetime' => time(),
                    ]);
                    model('\app\admin\model\express\Order')
                        ->where('id',$row['order_id'])
                        ->update([
                           'delivery_price' => $this->model->where('order_id',$row['order_id'])->sum('delivery_price') + $params['delivery_price']
                        ]);
                    $params['status'] = 4;
                    $result = $row->allowField(true)->save($params);
                    $ehund = new Ehund(Config::get('site.secretKey'), Config::get('site.callbackUrl'));
                    $is_express_no = model('app\api\model\Subscribe')->where(['express_no' => $params['express_no']])->count();
                    if($is_express_no == 0){
                        $returncode = $ehund->subScribe($params['express_com'], $params['express_no']);
                        if ($returncode['returnCode'] == 200) {
                            model('app\api\model\Subscribe')->create([
                                'sign' => $ehund->sign($params['express_no']),
                                'express_no' => $params['express_no'],
                                'returncode' => $returncode['returnCode'],
                                'message' => $returncode['message']
                            ]) ;
                        }

                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $list = $this->model
            ->with(['expressorder','user','goods'])
            ->whereIn('package.id',$ids)
            ->select();
        foreach ($list as $row){
            $row->getRelation('expressorder')->visible(['order_no']);
            $row->getRelation('user')->visible(['avatar','mobile']);
            $row['address'] = model('app\admin\model\express\OrderAddress')
                ->where(['order_id' => $row['order_id']])
                ->find();
            $row['express_name'] = Db::name('express_com')->where('code',$row['express_com'])->value('name');
        }
        $list = collection($list)->toArray();
        $comList = Db::name('express_com')->where('status','normal')->select();
        $this->view->assign("list", $list);
        $this->view->assign("row", $row);
        $this->view->assign("comList", $comList);
        return $this->view->fetch();
    }

    /**
     * 详情
     */
    public function detail($ids = null){
        $multi = $this->request->param('multi','');
        if($multi == 'order'){
            $list = $this->model
                ->with(['expressorder','user','goods'])
                ->whereIn('package.order_id',$ids)
                ->select();
        }else{
            $list = $this->model
                ->with(['expressorder','user','goods'])
                ->whereIn('package.id',$ids)
                ->select();
        }
        foreach ($list as $row){
            $row->getRelation('expressorder')->visible(['order_no']);
            $row->getRelation('user')->visible(['avatar','mobile']);
            $row['address'] = model('app\admin\model\express\OrderAddress')
                ->where(['order_id' => $row['order_id']])
                ->find();
            $row['express_name'] = Db::name('express_com')->where('code',$row['express_com'])->value('name');
            foreach ($row['goods'] as $key => $goods){
                $goods['category_name'] = Category::where('id',$goods['category_id'])->value('name');
                $goods['rule_name'] = \app\admin\model\express\Rule::where('id',$goods['rule_id'])->value('name');
            }
        }
        $list = collection($list)->toArray();
        $this->view->assign('list',$list);
        return $this->view->fetch();
    }


    /**
     * 创建批次并加入批次 && 加入批次
    */
    public function addBatch(){
        if($this->request->isPost()){
            $params = $this->request->post('row/a');
            $ids = explode(',',$params['ids']);
            Db::startTrans();
            try{
                if($params['type'] == 'new'){
                    $count = model('app\admin\model\express\Batch')->whereTime('createtime','today')->count();
                    $batch  = model('app\admin\model\express\Batch')->create([
                        'batch_no' => date('Ymd').'-'.($count + 1),
                        'number' => count($ids)
                    ]);
                    $batch_id = $batch['id'];
                }else{
                    $batch_id = $params['batch_id'];
                }
                $this->model->where('id','in',$ids)->setField('batch_id',$batch_id);
                $number = $this->model->where('batch_id',$batch_id)->count();
                model('app\admin\model\express\Batch')->where('id',$batch_id)->setField('number',$number);
                Db::commit();
            }catch (PDOException $e){
                $this->error($e->getMessage());
            }catch (Exception $e){
                $this->error($e->getMessage());
            }
            $this->success('操作成功');
        }

    }

    /**
     * 打印PDF
    */
    public function print($ids = null){
        Loader::import('tcpdf.tcpdf', EXTEND_PATH);
        // create new PDF document
        $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

// set document information
        $pdf->SetCreator(PDF_CREATOR);
        $pdf->SetAuthor('Nicola Asuni');
        $pdf->SetTitle(date('Y-m-d').'-'.time());
        $pdf->SetSubject('TCPDF Tutorial');
        $pdf->SetKeywords('TCPDF, PDF, example, test, guide');

// remove default header/footer
        $pdf->setPrintHeader(false);
        $pdf->setPrintFooter(false);

// set default monospaced font
        $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

// set margins
        $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);

// set auto page breaks
        $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

// set image scale factor
        $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);


        // ---------------------------------------------------------

        // set font
        $pdf->SetFont('stsongstdlight', 'B', 16);
        // 查询包裹
        $packageList = model('app\admin\model\express\Package')
            ->with(['goods'])
            ->where('id','in',$ids)
            ->select();
        // 循环包裹插入pdf
        foreach ($packageList as $package){
            $consigneeAddress = OrderAddress::get($package['address_id']);
            $deliveryAddress = Db::name('express_delivery_address')->find($package['delivery_address_id']);
            $goodsInfo = [];
            foreach ($package['goods'] as $goods){
                //$goodsInfo[] = $goods['name'].'*'.$goods['number'].'('.bcmul($goods['weight'],$goods['number'],2).$goods['unit'].')';
                $goodsInfo[] = str_replace(' ','',$goods['description'].'|'.$goods['sku'].'|'.$goods['weight'].$goods['unit'].'|'.$goods['number_unit'].'|*'.$goods['number']);
            }
            $goodsInfoStr = implode(';',$goodsInfo);
            // add a page
            $pdf->AddPage();
            $pdf->setJPEGQuality(75);
            $style = array(
                'position' => 'absolute',
                'align' => 'R',
                'stretch' => true,
                'fitwidth' => true,
                'cellfitalign' => '',
                'border' => false,
                'hpadding' => 'auto',
                'vpadding' => 'auto',
                'fgcolor' => array(0,0,0),
                'bgcolor' => false, //array(255,255,255),
                'text' => true,
                'font' => 'helvetica',
                'fontsize' => 12,
                'stretchtext' => 4
            );
            $pdf->Image(ROOT_PATH.'public/assets/img/ems.png', 15, 25, 90, 30, 'PNG', '', '', true, 150, '', false, false, 0, false, false, false);
            $pdf->Image(ROOT_PATH.'public/assets/img/ems.png', 135, 175, 60, 20, 'PNG', '', '', true, 150, '', false, false, 0, false, false, false);
            $pdf->Image(ROOT_PATH.'public/assets/img/check.png', 135, 253, 45, 15, 'PNG', '', '', true, 150, '', false, false, 0, false, false, false);
            // PRINT VARIOUS 1D BARCODES
            $pdf->Image(ROOT_PATH.'public/assets/img/logo.jpg', 155, 52, 32, 32, 'JPG', '', '', true, 150, '', false, false, 0, false, false, false);
            // CODE 39 - ANSI MH10.8M-1983 - USD-3 - 3 of 9.
            //$pdf->Cell(120, 25, $package['package_no'], '', 0, 'L', 0);
            $pdf->write1DBarcode($package['express_no'], 'C128', '100', '', '', 30, 0.9, $style, 'R');
            $pdf->Ln();
            $pdf->Cell(60, 10, '收件人:'.$consigneeAddress['name'], 'T', 0, 'L', 0);
            $pdf->Cell(75, 10, '收件电话:'.$consigneeAddress['mobile'], 'TR', 0, 'L', 0);
            $pdf->Cell(45, 10, '', 'T', 0, 'L', 0);
            $pdf->Ln();
            $pdf->MultiCell(135, 20, '收件地址:'.$consigneeAddress['province'].$consigneeAddress['city'].$consigneeAddress['area'].$consigneeAddress['address'], 'R', 'J', '', 0);
           /* $pdf->Cell(45, 15, '', '', 0, 'L', 0);*/
            $pdf->Ln();
            $pdf->Cell(90, 10, '寄件人:'.$deliveryAddress['name'], 'T', 0, 'L', 0);
            $pdf->Cell(90, 10, '寄件电话:'.$deliveryAddress['mobile'], 'T', 0, 'L', 0);
            $pdf->Ln();
            $pdf->MultiCell(180, 15, '寄件地址:'.$deliveryAddress['address'], '', 'J', '', 0);
            $pdf->Ln();
            $pdf->Cell(90, 10, '签收人', 'TR', 0, 'L', 0);
            $pdf->Cell(90, 10, '签收时间', 'T', 0, 'L', 0);
            $pdf->Ln();
            $pdf->Cell(90, 10, '', 'R', 0, 'C', 0);
            $pdf->Cell(45, 10, '', '', 0, 'C', 0);
            $pdf->Cell(15, 10, '年', '', 0, 'C', 0);
            $pdf->Cell(15, 10, '月', '', 0, 'C', 0);
            $pdf->Cell(15, 10, '日', '', 0, 'C', 0);
            $pdf->Ln();
            $pdf->Cell(90, 10, '配货信息:', 'TR', 0, 'L', 0);
            $pdf->Cell(90, 10, '重量:'.($package['weight'].'Kg'), 'T', 0, 'L', 0);
            $pdf->Ln();
            $pdf->MultiCell(90, 35, $goodsInfoStr, 'R', 'J', '');
            $pdf->Cell(180, 0, '', 'T', 0, 'L', 0);
            $pdf->write1DBarcode($package['express_no'], 'C128', 10, '', '', 30, 0.9, $style, '');
            $pdf->Ln();
            $pdf->Cell(90, 15, '寄件人:'.$deliveryAddress['name'], 'TR', 0, 'L', 0);
            $pdf->Cell(90, 15, '收件人:'.$consigneeAddress['name'], 'T', 0, 'L', 0);
            $pdf->Ln();
            $pdf->Cell(90, 15, '寄件电话:'.$deliveryAddress['mobile'], 'R', 0, 'L', 0);
            $pdf->Cell(90, 15, '收件电话:'.$consigneeAddress['mobile'], '', 0, 'L', 0);
            $pdf->Ln();
            $pdf->MultiCell(90, 20, '寄件地址:'.$deliveryAddress['address'], 'R', 'J', '', 0);
            $pdf->MultiCell(90, 20, '收件地址:'.$consigneeAddress['province'].$consigneeAddress['city'].$consigneeAddress['area'].$consigneeAddress['address'], 'L', 'J', '', 0);
            $pdf->Ln();
            $pdf->Cell(180, 20, '打印日期:'.date('Y-m-d'), 'TB', 0, 'L', 0);

            // ---------------------------------------------------------
        }


        //Close and output PDF document
        $pdf->Output(date('Y-m-d').'-'.time(), 'I');
        exit;
    }

    /**
     * 物流订阅
    */
    public function subscribe(){
        $id = $this->request->post('id');
        $row = $this->model->get($id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $ehund = new Ehund(Config::get('site.secretKey'), Config::get('site.callbackUrl'));
        $is_express_no = model('app\api\model\Subscribe')->where(['express_no' => $row['express_no']])->count();
        if($is_express_no == 0){
            $returncode = $ehund->subScribe($row['express_com'], $row['express_no']);
            if ($returncode['returnCode'] != 200) {
                $this->error('快递订阅接口异常-'.$returncode['message']);
            }
            model('app\api\model\Subscribe')->create([
                'sign' => $ehund->sign($row['express_no']),
                'express_no' => $row['express_no'],
                'returncode' => $returncode['returnCode'],
                'message' => $returncode['message']
            ]) ;
        }
        $this->success();
    }

    /**
     * 查看物流轨迹
    */
    public function track($ids = null){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $trackList = [];
        $track = model('app\api\model\PackageTrack')
            ->where('package_id',$ids)
            ->order('createtime asc')
            ->select();
        foreach ($track as $item){
            $desc = '';
            switch ($item['status']){
                case '0':
                    $desc = '包裹准备发货';
                    break;
                case '1':
                    $desc = '包裹已预报';
                    break;
                case '2':
                    $desc = '包裹发往库房';
                    break;
                case '3':
                    $desc = '库房已签收,正在处理包裹';
                    break;
                case '4':
                    $desc = '库房打包完成';
                    break;
                case '5':
                    $desc = '扫入邮袋,送往机场,等待起飞';
                    break;
                case '6':
                    $desc = '飞往中国';
                    break;
                case '7':
                    $desc = '到达中国';
                    break;
                case '8':
                    $desc = '清关中';
                    break;
                case '9':
                    $desc = '发送国内快递';
                    break;
            }
            $trackList[] = [
                'time' => date('Y-m-d H:i:s',$item['createtime']),
                'desc' => $desc,
                'memo' => $item['memo'],
            ];
        }
        if($row['status'] == '9'){
            $row['express_name'] = Db::name('express_com')->where('code',$row['express_com'])->value('name');
            $trackList[] = [
                'time' => $row['express_name'].$row['express_no'],
                'desc' => '国内快递单号',
                'memo' => '',
            ];

            $express = model('app\api\model\Subscribe')
                ->where(['express_no' => $row['express_no']])
                ->find();
            if($express){
                $expressList = json_decode($express['data'], true);
                foreach ($expressList as $item){
                    $trackList[] = [
                        'time' => $item['time'],
                        'desc' => $item['context'],
                        'memo' => '',
                    ];
                }
            }else{
                $trackList[] = [
                    'desc' => '打包完成，正在等待快递小哥揽收~',
                    'time' => date('Y-m-d H:i:s',model('app\api\model\PackageTrack')
                        ->where('package_id',$ids)
                        ->where('status','9')
                        ->value('createtime')),
                    'memo' => '',
                ];
            }
        }
        $trackList = array_reverse($trackList);
        $this->view->assign('trackList',$trackList);
        return $this->view->fetch();
    }


    /*
     * 修改重量/容量
     * */
    public function editWeight(){
        $id = $this->request->post('id');
        $weight = $this->request->post('weight');
        $row = model('app\admin\model\express\PackageGoods')->get($id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $params = [
            'weight' => $weight
        ];
        $result = false;
        $result = $row->allowField(true)->save($params);
        if ($result !== false) {
            $this->success();
        } else {
            $this->error(__('修改失败'));
        }
    }
}
